<template>
  <div style=" margin-right: calc(100% - 100vw);">
    <div class="center" v-infinite-scroll="loadNewTimePosts" infinite-scroll-distance="1"
      infinite-scroll-disabled="disabled" style="height: 100vh">
      <div class="profile">
        <el-input v-model="studyQueryVo.value" @keyup.enter.native="getStudyBookByDemand()" ref="myInput"
          placeholder="请输入关键字搜索"></el-input>
        <el-button style="width: 20%; margin-left: 10px" round icon="el-icon-search"
          @click="getStudyBookByDemand()">搜索资料</el-button>


      </div>

      <div class="SearchClassType ">
        <div :class="{ classAvtive: studyQueryVo.isPrivate === '' }" @click="set_search_class_type('')">
          全部
        </div>
        <div :class="{ classAvtive: studyQueryVo.isPrivate === false }" @click="set_search_class_type(false)">
          公开
        </div>
        <div :class="{ classAvtive: studyQueryVo.isPrivate === true }" @click="set_search_class_type(true)">
          仅社团
        </div>

      </div>
      <div class="FatherClass">
        <div :class="{ SletctAvtive: one_class === '' }" @click="set_one_class('')">
          全部
        </div>
        <div v-for="(v, i) in options" :key="i" :class="{ SletctAvtive: one_class === v.parentId }"
          @click="set_one_class(v.parentId)">
          {{ v.pname }}
        </div>
      </div>
      <div class="ChildClass">
        <div :class="{ SletctAvtive: two_class === '' }" @click="set_two_class('')">
          不限
        </div>
        <div v-for="(v, i) in getTwoClass()" :key="i" :class="{ SletctAvtive: two_class === v.id }"
          @click="set_two_class(v.id)">
          {{ v.name }}
        </div>
      </div>

      <div>
        <div class="showContent">

          <div v-for="(item, index) in StudyData" :key="index" class="study-item">
            <div class="study-item-header">
              <h5 :title="item.title" style="cursor:default;  width:100% ;display:inline-block; overflow:hidden; white-space
                    :nowrap;text-overflow:ellipsis;  font-size: 19px;margin-bottom: 3px;">{{ item.title }}</h5>
              <el-tag type="primary"
                style="padding: 0px 5px ;  font-size: 13px;height: fit-content;line-height: 20px;margin-top: 10px;">{{
                  item.typeName }}</el-tag>
            </div>


            <p :title="item.description" style="max-height: 40px; max-width: 400px; display: -webkit-box; line-clamp: 2; -webkit-box-orient: vertical;  width: 80%; height: 34%; white-space:wrap; overflow:hidden; text-overflow:ellipsis;
                  font-size: 14px;position:absolute; margin-top:0;padding-top:0 ;padding-right: 7px;">
              {{ item.description }}</p>

            <div class="study-item-footer">
              <div style="margin-right: 1vw;  font-size: 2vh;width: 20px;">
                <div>
                  <!-- 查看量 -->
                  <span><svg-icon icon-class="watchs" /> <span style="color:rgb(138,138,138)"> {{
                    item.views }}</span></span>

                  <!-- 点赞 -->
                  <span class="dz" @click="toggleLike(item.id, item.likes)">
                    <svg-icon icon-class="giveTheThumbs-up" v-show="!item.isGiveTheThumbs_up" />
                    <svg-icon icon-class="redGiveTheThumbs-up" v-show="item.isGiveTheThumbs_up" />
                    <span style="color:rgb(138,138,138)">{{ item.likes }}</span>
                  </span>
                  <!-- 收藏 -->
                  <span class="sc marginsLeft" @click="toggleCollect(item.id, item.collects)">
                    <svg-icon icon-class="collection" v-show="!item.isCollects" />
                    <svg-icon icon-class="collectionAfter" v-show="item.isCollects" />
                    <span style="color:rgb(138,138,138)">{{ item.collections }}</span>
                  </span>


                </div>

                <div style="font-size: 17px; color:rgb(138,138,138)"> {{ item.gmtModified.substring(0, 10) }} </div>
              </div>



              <a v-if="item.isPrivate === false" :href="item.fileUrl" target="_blank"><el-button
                  @click="updateViewCount(item.id)" class="study-item-footer-btn" style="width: 108px; position: absolute;top : 10px;right: 15px;width: 70px;
      padding-left: 20px;margin-left: 11vh ; background-color: rgb(221,242,255);" round>查看</el-button></a>


              <div v-if="item.isPrivate === true">

                <a v-if="$store.state.isJoin" :href="item.fileUrl" target="_blank">
                  <el-button @click="updateViewCount(item.id)" class="study-item-footer-btn"
                    style="background-color: rgb(221,242,255) ;position: absolute;top : -10px;top: 10px; right: 15px;width: 108px;padding-left: 10px;margin-left: 11vh; "
                    round>
                    协会内部资料 </el-button></a>



                <el-button v-else class="study-item-footer-btn"
                  style="background-color: rgb(221,242,255) ;position: absolute;top : 10px;right: 15px;width: 108px;padding-left: 10px;margin-left: 11vh; "
                  round>

                  <div>协会内部资料</div>
                </el-button>
              </div>

              <div class="study-item-footer-btn">

                <div v-if="item.isPrivate === true" class="study-item-footer">
                </div>
              </div>
            </div>
          </div>
          <div style="opacity: 0;" class="study-item" v-if="StudyData.length % 3 === 2"></div>

        </div>
        <div class="hot-topic">
          <h3>热门资源分享</h3>
          <div class="time">更新于：{{ currentTime }}</div>
          <div class="content">
            <ul>
              <li v-for="(item, index) in postRanking" :key="index">
                <span>{{ index + 1 }}</span>
                <span @click="updateViewCount(item.id)"><a v-if="item.isPrivate === false" :href="item.fileUrl"
                    target="_blank"">{{ item.title }}</a></span>
                <span>{{ item.score }}</span>
              </li>
              <!-- <li>111</li>
              <li>111</li>
              <li>111</li>
              <li>111</li>
              <li>111</li> -->
            </ul>
          </div>
        </div>
      </div>

      <p style=" text-align: center" v-if="loading">加载中...</p>
                    <el-empty description="暂无数据" v-if="!StudyData.length"></el-empty>
          </div>
        </div>
</template>






<script>
import { getAllStudyType, getStudyBook, updateViewCount, getCurrentTime, getStudyDataByScore } from "@/api/comment/index.js";
import { goodLike, goodCollect } from "../../api/service-good/goodService";
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      collectForm: {
        id: "",
        type: 3,
      },
      likeForm: {
        id: "",
        type: 3,
      },
      test: "测试数据",
      // clientHeight: 0,
      // // 页面高度
      // scrollTop: 0,
      // //滚动条位置
      // bodyHeight: 0,
      studyPage: 1,
      // 学习资料分页
      studyLimit: 12,
      // 学习资料每页显示数量
      studyQueryVo: {
        isPrivate: '',
        parentTypeId: '',
        typeId: '',
        value: ''
      },
      //这只是样子货，实际上要从接口返回学习资料的数据
      StudyData: [],
      SearchKeyword: "",
      typeId: [],
      types: [],
      one_class: "",
      two_class: "",
      isPrivate: false,
      options: [],
      sumpage: 1,
      queryVo: {
        parentId: '',
        // 设置 typeId 为一个空数组，符合子类型集合的要求
        typeId: [],
        description: '',
        gmtCreate: '',
        gmtModified: '',
        id: '',
        isDeleted: false,
        name: ''
      },

      page: 1,
      // 每页查询的数量，初始化为10
      limit: 50,
      // 加载状态，初始化为false
      loading: false,
      // 用于存储查询到的数据列表
      dataList: [],
      disabled: false, // 控制是否禁用下拉加载
      currentTime: "", //当前时间
      postRanking: [], //帖子排名
    }
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {

    async loadNewTimePosts() {
      // 防止重入
      if (this.loading || this.disabled) return;

      this.loading = true; // 开始加载状态
      this.studyPage++; // 页码+1

      try {
        await this.getStudyBookone(); // 加载新数据
        await this.queryCurrentTime();//获取时间
        await this.queryStudyDataByScore();
      } catch (error) {
        console.error('加载数据失败:', error);
      } finally {
        this.loading = false; // 重置加载状态
        // 检查是否还有更多数据可以加载
        this.disabled = (this.studyPage >= this.sumpage);
      }
    },
    // 其他方法...

    toggleLike(id, likes) {
      this.likeForm.id = id;

      goodLike(this.likeForm).then((res) => {
        if (res.code == 20000) {
          this.StudyData.forEach((item) => {
            if (item.id == id) {
              item.isGiveTheThumbs_up = !item.isGiveTheThumbs_up;
              if (item.isGiveTheThumbs_up) {
                this.$message.success("点赞成功");
                item.likes += 1;
              } else {
                //this.$message.success("取消点赞成功");
                item.likes -= 1;
              }
            }
          });
        } else {
          this.$message.error("点赞失败，请稍后再试！");
        }
      });
    },
    //收藏
    toggleCollect(id, collects) {
      this.collectForm.id = id;

      goodCollect(this.collectForm).then((res) => {
        if (res.code == 20000) {
          this.StudyData.forEach((item) => {
            if (item.id == id) {
              console.log(item);
              item.isCollects = !item.isCollects;
              if (item.isCollects) {
                this.$message.success("收藏成功");
                item.collections += 1;
                console.log(item.collects);
              } else {
                //this.$message.success("取消收藏成功");
                item.collections -= 1;
              }
            }
          });
        } else {
          this.$message.error("收藏失败，请稍后再试！");
        }
      });
    },

    updateViewCount(id) {
      updateViewCount(id).then((res) => {
        console.log(res, '更新查看量');
      });
    },

    getStudyBookone() {
      return new Promise((resolve, reject) => {
        getStudyBook(this.studyPage, this.studyLimit, this.studyQueryVo).then((res) => {
          console.log(res);
          this.StudyData = [...this.StudyData, ...res.data.list.records.map((record) => ({
            ...record,
            isGiveTheThumbs_up: record.isLiked,
            isCollects: record.isCollected,
          }))];

          console.log(this.StudyData);
          this.studyPage = res.data.list.current;
          this.sumpage = res.data.list.pages;
          console.log(res, 'res', this.sumpage, ':sumpage总页数');

          resolve();  // 确保完成后解析 Promise
        }).catch((err) => {
          console.log(err);
          reject(err);  // 捕获错误并拒绝 Promise
        }).finally(() => {
          this.loading = false;
        });
      })

    },
    getStudyBookByDemand() {
      this.StudyData = [];
      this.studyPage = 1;
      this.getStudyBookone();
    },
    getTwoClass() {
      let arr = this.options.filter((item) => item.parentId === this.one_class);
      console.log(arr, arr[0], 'arr');
      return arr && arr[0] ? arr[0].studyTypeList : [];
    },
    // 热搜时间
    queryCurrentTime() {
      getCurrentTime().then((res) => {
        if (res.code === 20000) {
          this.currentTime = res.data.date;
        }
      });
    },

    // 热搜热度
    queryStudyDataByScore() {
      getStudyDataByScore().then((res) => {
        if (res.code === 20000) {
          // 使用 map 方法遍历 res.data.list，并处理每个元素的 score 属性
          this.postRanking = res.data.list.map((item) => {
            // 使用 Math.floor 或 parseInt 截取 score 的整数部分
            return {
              ...item, // 保留原始对象的其他属性
              score: (Number(String(item.score).slice(0, 6)) * 100).toFixed(2),//String转换成字符串，截取前6位，再Number转换成数字，最后使用toFixed保留两位小数
            };
          });
        }
        console.log(this.postRanking);
      });
    },
    set_two_class(value) {
      this.studyQueryVo.value = "";
      this.two_class = value;
      this.typeId[0] = this.two_class;
      this.studyQueryVo.typeId = this.two_class
      this.getStudyBookByDemand();
    },
    set_one_class(value) {
      this.studyQueryVo.value = "";
      this.one_class = value;
      this.two_class = "";
      this.studyQueryVo.parentTypeId = value;
      this.studyQueryVo.typeId = '';
      this.getStudyBookByDemand();
    },
    set_search_class_type(value) {
      if (value && !this.$store.state.isJoin) {
        console.log(this.$store.state.isJoin, '9999999');
        this.$message.warning("您还不是社团成员，快快加入吧");
        return;
      }
      this.studyQueryVo.isPrivate = value;
      this.getStudyBookByDemand();
    },


    getAllStudy() {

      getAllStudyType().then((res) => {

        console.log('111', res, '222');

        this.options = res.data.tree;
        console.log(this.options);

      });
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  async created() {

    await this.getAllStudy()

  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  async mounted() {
    this.$refs.myInput.focus();
    this.getStudyBookone()
    this.queryCurrentTime();
    this.queryStudyDataByScore();

  },
  beforeCreate() { }, //生命周期 - 创建之前
  beforeMount() { }, //生命周期 - 挂载之前
  beforeUpdate() { }, //生命周期 - 更新之前
  updated() { }, //生命周期 - 更新之后
  beforeDestroy() { }, //生命周期 - 销毁之前
  destroyed() { }, //生命周期 - 销毁完成
  activated() { }, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  list-style: none;
}

.study-item-header {

  justify-content: space-between;
  display: flex;
}

.study-item-footer-an {
  padding: 0;

}

.studybookloading {
  margin: 0 auto;
  margin-top: 10px;
}

.showContent {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.study-item {
  display: inline-block;
  /* background-image:url(../../assets/img/学习资料背景图.jpg); */
  background-image: linear-gradient(rgba(186, 224, 255), rgb(245, 255, 255));
  height: 150px;
  width: 250px;
  margin-top: 20px;
  border-radius: 6%;
  padding: 10px 20px;
  position: relative;
  transition: scale 6s ease-in-out;
}

.study-item:hover {
  box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.3);
  transform: scale(1.01);
}

.study-item-footer {
  width: 100%;
  position: absolute;
  left: 10px;
  margin-bottom: 10px;
  bottom: 0;
  display: flex;

  align-items: center;

}

.study-item-footer div {
  font-size: 14px;
  white-space: nowrap;
}

.study-item-footer a {
  color: black;
  text-decoration: none;
}

.study-item-footer span {
  cursor: pointer;
  font-size: 14px;
}

.study-item-footer-btn {
  color: #777777;
  font-weight: 700;
}

.study-item-footer-btn:hover {
  color: rgb(70, 100, 180);
  font-weight: 700;
}

.study-item h5 {
  font-size: 2vh;
  margin-top: 10px;
  margin-bottom: 10px;
}

.study-item p {
  font-size: 1.5vh;
  margin-top: 10px;
  margin-bottom: 10px;
}

.center {
  /* width: 100%; */
  display: flex;
  flex-direction: column;
  padding: 0 31% 0 16%;
  /* align-items: center; */
}

.profile {
  margin-top: 25px;
  display: flex;
  width: 100%;
  background-color: #fff;
  color: #505050;
  font-size: 18px;
}

.SearchClassType {
  justify-content: space-around;
}

.SearchClassType div {
  display: inline-block;
  padding: 10px 40px 3px 40px;
  margin: 20px 0 5px 0;
  flex: 1;
  cursor: pointer;
}

.classAvtive {
  color: rgb(70, 100, 180);
  border-bottom: 2px solid rgb(70, 100, 180);
  background: linear-gradient(rgba(133, 254, 254, 0.493), rgb(255, 255, 255));
  border-radius: 15px 15px 0px 0px;
}

.FatherClass {
  display: flex;
  font-size: 15px;
  font-weight: bold;
}

.FatherClass div {
  padding: 0px 20px 3px 10px;
  margin-bottom: 5px;
  cursor: pointer;
}

.ChildClass {
  display: flex;
  background: #f5f5f5;
  font-size: 13px;
}

.ChildClass div {
  padding: 10px 10px 5px 10px;
  margin-bottom: 5px;
  cursor: pointer;
}

.SletctAvtive {
  color: rgb(98, 70, 180);
}

.el-button.is-round {
  border-radius: 20px;
  padding: 8px 23px;
}

/* 热搜 */
.hot-topic {
  border: 1px solid lightgrey;
  box-shadow: 2px 2px 6px lightgray;
  border-radius: 6px;
  width: 400px;
  position: fixed;
  left: 70%;
  top: 125px;
  z-index: 100;
}

.hot-topic h3 {
  font-size: 20px;
  color: #fff;
  text-align: center;
  background-color: #0080ff;
  margin: 10px 0;
}

.hot-topic .time {
  height: 16px;
  font-size: 14px;
  margin: 5px 20px;
}

.hot-topic .content ul {
  list-style: none;
  padding: 0px;
  margin: 10px 0;
}

.hot-topic .content ul li {
  height: 45px;
  font-size: 16px;
  border-bottom: 1px dotted #ddd;
  margin-right: 10px;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.hot-topic span:nth-child(2) {
  width: 240px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}

.hot-topic span:nth-child(2) a {
  width: 240px;
  height: 45px;
  color: black;
  text-decoration: none;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}

.hot-topic li:nth-child(1) span:nth-child(1) {
  color: red;
  font-weight: bold;
}

.hot-topic li:nth-child(2) span:nth-child(1) {
  color: #ff5c55;
  font-weight: bold;
}

.hot-topic li:nth-child(3) span:nth-child(1) {
  color: #ffa552;
  font-weight: bold;
}
</style>
